package com.ruoyi.web.controller.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.user.TemplateException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mongo.AllSchoolDao;
import com.ruoyi.system.mongo.WorksDao;
import com.ruoyi.system.service.CompeWorkScroingRecordService;
import com.ruoyi.system.service.ISysCertificateSchoolService;
import com.ruoyi.system.service.ISysCertificateService;
import com.ruoyi.system.service.ISysCertificateTeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author HP
 * @Date 2021/3/3
 * @Description TODO
 */
@Api("排名颁发")
@RestController
@RequestMapping("/system/CompeWorkScroingRecord")
public class CompeWorkScroingRecordController {
    @Autowired
    private CompeWorkScroingRecordService compeWorkScroingRecordService;

    @Autowired
    private WorksDao worksDao;

    @Autowired
    private AllSchoolDao allSchoolDao;

    @Autowired
    private ISysCertificateService iSysCertificateService;

    @Autowired
    private ISysCertificateTeacherService iSysCertificateTeacherService;

    @Autowired
    private ISysCertificateSchoolService iSysCertificateSchoolService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @GetMapping("/GenerateSchoolCertificates/{epid}")
    @ApiOperation("在排名公布后根据赛事id生成学校证书")
    public AjaxResult GenerateSchoolCertificates(@PathVariable Integer epid) {
        //查询是否有未公布的信息
        Integer ccount = compeWorkScroingRecordService.queryCompeWorkScroingRecordByPublicStatus(epid);
        if(ccount>0) {
            return AjaxResult.error("请先公布排名！");
        }
        //根据赛事id获取生成证书所需要的所有信息
        List<SysCertificateAll> sysCertificateAlls = compeWorkScroingRecordService.querySysCertificateAllSchoolByEpid(epid);
        boolean state=false;
        for (int i = sysCertificateAlls.size() -1; i>=0; i--) {
            SysCertificateAll sysCertificateAll = sysCertificateAlls.get(i);
            SysCertificateSchool sysCertificateSchool=new SysCertificateSchool();
            sysCertificateSchool.setEpid(sysCertificateAll.getEpid());
            sysCertificateSchool.setSchoolid(allSchoolDao.queryByNames(sysCertificateAll.getSchooName()).get_id());
            //查询是否有重复学生证书信息
            Integer count = iSysCertificateSchoolService.queryCertificateSchoolIsNull(sysCertificateSchool);
            if(count>0){
                state=true;
                sysCertificateAlls.remove(i); //如果已发证书，从列表中去除
                continue;
            }
//            compeWorkScroingRecordService.generateSchoolCertificates(sysCertificateAlls);
        }
        if(state==true) {
            return AjaxResult.error("已为该赛事的获奖学校颁发过证书,请勿重复操作！！！");
        }

        try {
            //循环生成所有教师证书信息
            compeWorkScroingRecordService.generateSchoolCertificates(sysCertificateAlls);
        } catch (TemplateException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getCode(), e.getMessage());
        }
        return AjaxResult.success();
    }



    @GetMapping("/GenerateTeacherCertificates/{epid}")
    @ApiOperation("在排名公布后根据赛事id生成老师证书")
    public AjaxResult GenerateTeacherCertificates(@PathVariable Integer epid) {
        //查询是否有未公布的信息
        Integer ccount = compeWorkScroingRecordService.queryCompeWorkScroingRecordByPublicStatus(epid);
        if(ccount>0){
            return AjaxResult.error("请先公布排名！");
        }
        //根据赛事id获取生成证书所需要的所有信息
        List<SysCertificateAll> sysCertificateAlls = compeWorkScroingRecordService.querySysCertificateAllTeacherByEpid(epid);
        boolean state=false;
        for (int i = sysCertificateAlls.size() -1; i>=0; i--) {
            SysCertificateAll sysCertificateAll = sysCertificateAlls.get(i);
            SysCertificateTeacher sysCertificateTeacher=new SysCertificateTeacher();
            sysCertificateTeacher.setEpid(sysCertificateAll.getEpid());
            sysCertificateTeacher.setTeacher(sysCertificateAll.getTeacherId());
            //查询是否有重复学生证书信息
            Integer count = iSysCertificateTeacherService.queryCertificateTeacherIsNull(sysCertificateTeacher);
            if(count>0){
                state=true;
                sysCertificateAlls.remove(i); //如果已发证书，从列表中去除
                continue;
            }
        }
        if(state==true) {
            return AjaxResult.error("已为该赛事的获奖老师颁发过证书,请勿重复操作！！！");
        }
        try {
            //循环生成所有教师证书信息
            compeWorkScroingRecordService.generateTeacherCertificates(sysCertificateAlls);
        } catch (TemplateException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getCode(), e.getMessage());
        }
        return AjaxResult.success();
    }




    @GetMapping("/GenerateStudentCertificates/{epid}")
    @ApiOperation("在排名公布后根据赛事id生成学生证书")
    public AjaxResult GenerateStudentCertificates(@PathVariable Integer epid) {
        //查询是否有未公布的信息
        Integer ccount = compeWorkScroingRecordService.queryCompeWorkScroingRecordByPublicStatus(epid);
        if(ccount>0){
            return AjaxResult.error("请先公布排名！");
        }
        //根据赛事id获取生成证书所需要的所有信息
        List<SysCertificateAll> sysCertificateAlls = compeWorkScroingRecordService.querySysCertificateAllStudentByEpid(epid);
        boolean state=false;
        for (int i = sysCertificateAlls.size() -1; i>=0; i--) {
            SysCertificateAll sysCertificateAll = sysCertificateAlls.get(i);
            SysCertificate sysCertificate=new SysCertificate();
            sysCertificate.setEpid(sysCertificateAll.getEpid());
            sysCertificate.setStuid(sysCertificateAll.getSid());
            sysCertificate.setProduction(sysCertificateAll.getWork_id());
            //查询是否有重复学生证书信息
            Integer count = iSysCertificateService.queryCertificateIsNull(sysCertificate);
            if(count>0){
                state=true;
                sysCertificateAlls.remove(i); //如果已发证书，从列表中去除
                continue;
            }
        }

        if(state==true){
            return AjaxResult.error("已为该赛事的获奖学生颁发过证书,请勿重复操作！！！");
        }

        try {
            //循环生成所有学生证书信息
            compeWorkScroingRecordService.generateStudentCertificates(sysCertificateAlls);
        } catch (TemplateException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getCode(), e.getMessage());
        }
        return AjaxResult.success();
    }


    @GetMapping("/queryWorksRecordByTid")
    @ApiOperation("教师端根据教师id和学校名称查询已评审过作品记录")
    public AjaxResult queryWorksRecordByTid(CompeWorkScroingRecord compeWorkScroingRecord,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<CompeWorkScroingRecord> workList = compeWorkScroingRecordService.queryWorksRecordByTid(compeWorkScroingRecord);
        PageInfo<CompeWorkScroingRecord>  pageInfo=new PageInfo<>(workList);
        return AjaxResult.success(pageInfo);
    }

    @GetMapping("/queryWorksRecordByAdmin")
    @ApiOperation("系统管理员或后台评审员查询已评审过作品记录")
    public AjaxResult queryWorksRecordByAdmin(CompeWorkScroingRecord compeWorkScroingRecord,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<CompeWorkScroingRecord> workList = compeWorkScroingRecordService.queryWorksRecordByAdmin(compeWorkScroingRecord);
        PageInfo<CompeWorkScroingRecord>  pageInfo=new PageInfo<>(workList);
        return AjaxResult.success(pageInfo);
    }

    @GetMapping("/queryCompetitionRankingAnnouncement")
    public AjaxResult queryCompetitionRankingAnnouncement(CompeWorkScroingRecord compeWorkScroingRecord,Integer pageNum,Integer pageSize){
        List<CompeWorkScroingRecord> compeWorkScroingRecordsList = compeWorkScroingRecordService.queryCompetitionRankingAnnouncement(compeWorkScroingRecord,pageNum,pageSize);
//        List<Works> worksList = worksDao.queryWorks();
//        //循环
//        for (Works works : worksList) {
//            System.out.println(works);
//            for (CompeWorkScroingRecord compeWorkScroingRecords : compeWorkScroingRecordsList) {
//                //判断学生表id字段和证书信息表的stuid字段是否对应
//                System.out.println(compeWorkScroingRecords.getWork_id().equals(works.get_id()));
//                if(compeWorkScroingRecords.getWork_id().equals(works.get_id())){
//                    //对应则将证书信息表的学生姓名改为用户表中的nickname
//                    compeWorkScroingRecords.setTitle(works.getTitle());
//                }
//            }
//        }
        for (CompeWorkScroingRecord compeWorkScroingRecord1 : compeWorkScroingRecordsList) {
            if (StringUtils.isBlank(compeWorkScroingRecord1.getNickname())){
                compeWorkScroingRecord1.setNickname("管理员");
            }
        }
        PageInfo pageInfo = new PageInfo(compeWorkScroingRecordsList);
        return AjaxResult.success(pageInfo);
    }


    @PutMapping("/batchUpdateRanking")
    public AjaxResult batchUpdateRanking(@RequestBody List<CompeWorkScroingRecord> list){
        for (CompeWorkScroingRecord compeWorkScroingRecord : list) {
            compeWorkScroingRecordService.updateRanking(compeWorkScroingRecord);
        }
        return AjaxResult.success();
    }


    @PutMapping("/updateRanking")
    public AjaxResult updateRanking(CompeWorkScroingRecord compeWorkScroingRecord){
        compeWorkScroingRecordService.updateRanking(compeWorkScroingRecord);
        return AjaxResult.success();
    }

    /**
     * 公布比赛排名
     * @param compeWorkScroingRecord
     * @return
     */
    @PutMapping("/updatePublicStatus")
    public AjaxResult updatePublicStatus(CompeWorkScroingRecord compeWorkScroingRecord){
        try {
            compeWorkScroingRecordService.updatePublicStatus(compeWorkScroingRecord);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 评分完成后添加评分信息
     * @param compeWorkScroingRecord
     */
    @PostMapping("/saveCompeWorkScroingRecord")
    @ApiOperation("评分完成后添加评分信息")
    public AjaxResult saveCompeWorkScroingRecord(CompeWorkScroingRecord compeWorkScroingRecord) {
        System.out.println("compeWorkScroingRecord ==== " + compeWorkScroingRecord);
        if(compeWorkScroingRecord.getScoring_id()==null
                && compeWorkScroingRecordService.queryCompeWorkScroingRecordIsNull(compeWorkScroingRecord)!=null){
            return AjaxResult.error("不可重复评审!!!");
        }

        compeWorkScroingRecordService.saveCompeWorkScroingRecord(compeWorkScroingRecord);
        //获取缓存评审使用的key
        String key = compeWorkScroingRecord.getCompe_id() + "_" + compeWorkScroingRecord.getWork_id();
        redisTemplate.delete(key); //从redis缓存中去除
        return AjaxResult.success(compeWorkScroingRecord.getScoring_id());
    }
}
